import AMapLoader from '@amap/amap-jsapi-loader'
import * as THREE from 'three'
import { options } from './district'
import { GeoData, Item } from './types'

/**
 * @description 获取指定行政区划地图数据（three + dataV方式）
 * @param adcode 行政区划编码
 * @param urlSuffix 是否包含子区域（默认包含）
 * @returns 该行政区划地图数据
 */
export function getDistrictGeoDataByDataV(adcode: string, urlSuffix = '_full') {
  const loader = new THREE.FileLoader()
  const lastTwoEle = adcode.slice(4)

  let url = `https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=${adcode}${urlSuffix}`

  /** 区县级无子区域 */
  if (lastTwoEle !== '00') {
    url = `https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=${adcode}`
  }

  return new Promise((resolve, reject) => {
    loader.load(url, (data: any) => {
      if (data) {
        const jsonData = JSON.parse(data)
        console.log(jsonData)
        resolve(jsonData)
      } else {
        reject('加载数据失败！')
      }
    })
  })
}

/**
 * @description 获取指定行政区划地图数据（loadUI方式）
 * @param adcode 行政区划编码
 * @param childAdcode 子级行政区划编码
 * @returns 该行政区划地图数据
 */
export function getDistrictGeoData(adcode: number | string, childAdcode = '') {
  /** 挂载AMapUI */
  const loadAMap = async () => {
    /** 只在初次挂载 */
    if (!window?.AMap) {
      await new Promise((resolve) => {
        return AMapLoader.load({
          key: '60fdb942e15dfeefff0d5595c58a8de3', // 申请好的Web端开发者Key，首次调用 load 时必填
          version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          // 需要使用的的插件列表，如比例尺'AMap.Scale'等
          AMapUI: {
            // 是否加载 AMapUI，缺省不加载
            version: '1.1', // AMapUI 版本
            plugins: ['overlay/SimpleMarker'] // 需要加载的 AMapUI ui插件
          }
        }).then(async (AMap: any) => {
          window.AMap = AMap
          resolve('加载成功！')
        })
      })
    }
  }

  /** 获取行政区划数据 */
  const getGeoJson = async (adcode: number | string, childAdcode = ''): Promise<GeoData> => {
    await loadAMap()
    return new Promise((resolve, reject) => {
      const insideFun = (adcode: string | number, childAdcode: string | number) => {
        window.AMapUI.loadUI(['geo/DistrictExplorer'], (DistrictExplorer: any) => {
          const districtExplorer = new DistrictExplorer()
          districtExplorer.loadAreaNode(adcode, function (error: any, areaNode: any) {
            if (error) {
              reject(error)
              return
            }
            let Json = areaNode.getSubFeatures()

            if (Json.length === 0) {
              const parent = areaNode._data.geoData.parent.properties.acroutes
              insideFun(parent[parent.length - 1], adcode)
              return
            }

            if (childAdcode) {
              Json = Json.filter((item: any) => {
                return item.properties.adcode == childAdcode
              })
            }
            const mapJson = {
              features: Json
            }

            resolve(mapJson)
          })
        })
      }
      insideFun(adcode, childAdcode)
    })
  }

  return getGeoJson(adcode)
}

/** 直辖市和特别行政区的adcode */
export const special_city = [
  // 北京市
  '110000',
  // 上海市
  '310000',
  // 重庆市
  '500000',
  // 天津市
  '120000',
  // 香港特别行政区
  '810000',
  // 澳门特别行政区
  '820000'
]

/**
 * @description 根据行政区划编码获取完整省市区面包屑路径
 * @param adcode 行政区划编码
 * @param curItem 当前选项完整信息, 如果不传，则会根据adcode，查找对应上下链
 * @param level 数据保留层级，搜索结果保留最深一级，如只到市一级的地图，则截去区县信息
 * @returns 行政区划具体路径
 */
export function getDistrictRoutesInfo(adcode: string, curItem?: Item, level = 3): Array<Item> {
  const country = options[0]
  /** 选中了全国 */
  if (adcode === '100000') return [country]

  const lastTwoEle = adcode.slice(4)
  const lastFourEle = adcode.slice(2)

  /** 选中了省和直辖市、特别行政区 */
  if (lastFourEle === '0000') {
    const province = options.find((k) => k.adcode === `${adcode}`) as Item
    return [country, curItem || province].slice(0, level)
  }

  /** 选中了市 */
  if (lastTwoEle === '00') {
    const province = options.find((k) => k.adcode === `${adcode.slice(0, 2)}0000`) as Item
    const city = (province.children as Item[]).find((k) => k.adcode === `${adcode}`) as Item
    return [country, province, curItem || city].slice(0, level)
  }

  /** 选中了区县 */
  if (lastTwoEle !== '00') {
    const province = options.find((k) => k.adcode === `${adcode.slice(0, 2)}0000`) as Item

    /** 如果是直辖市和特别行政区, 则没有市级选项, 直接返回区县级, 且数据保留层级level - 1 */
    if (special_city.includes(province.adcode)) {
      const area = (province.children as Item[]).find((k) => k.adcode === `${adcode}`) as Item
      return [country, province, curItem || area].slice(0, level - 1)
    }

    /** 有则返回省市区县 */
    const city = (province.children as Item[]).find(
      (k) => k.adcode === `${adcode.slice(0, 4)}00`
    ) as Item
    const area = (city.children as Item[]).find((k) => k.adcode === `${adcode}`) as Item
    return [country, province, city, curItem || area].slice(0, level)
  }

  return [country]
}
